package com.webproject.shop.controller;

import com.webproject.shop.common.BusinessException;
import com.webproject.shop.common.ErrorCode;
import com.webproject.shop.common.ResponseModel;
import com.webproject.shop.pojo.User;
import com.webproject.shop.service.UserService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.webproject.shop.common.ToolBox;

import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/user")
@CrossOrigin(origins = "${webproject.web.path}", allowedHeaders = "*", allowCredentials = "true")

public class UserController implements ErrorCode {
    @Autowired
    private UserService userService;

    @RequestMapping(path = "/register", method = RequestMethod.POST)
    @ResponseBody
    public ResponseModel register(User user, HttpSession session) {
        // 加密处理
        user.setPassword(ToolBox.md5(user.getPassword()));
        // 注册用户
        userService.register(user);
        return new ResponseModel();
    }

    @RequestMapping(path = "/login", method = RequestMethod.POST)
    @ResponseBody
    public ResponseModel login(String username, String password, HttpSession session) {
        if (StringUtils.isEmpty(username)
                || StringUtils.isEmpty(password)) {
            throw new BusinessException(PARAMETER_ERROR , "参数不合法！");
        }
        String md5pwd = ToolBox.md5(password);
        User user = userService.login(username, md5pwd);
        session.setAttribute("loginUser", user);
        return new ResponseModel(user);
    }

    @RequestMapping(path = "/logout", method = RequestMethod.GET)
    @ResponseBody
    public ResponseModel logout(HttpSession session,String token) {
        session.invalidate();
        return new ResponseModel();
    }
    @RequestMapping(path = "/status", method = RequestMethod.GET)
    @ResponseBody
    public ResponseModel getUser(HttpSession session) {
        User user = (User) session.getAttribute("loginUser");
        return new ResponseModel(user);
    }
}
